﻿#include "computerdisplaywidget.h"
#include "ui_computerdisplaywidget.h"
#include "dbservice.h"
#include <QMessageBox>
#include "computerwindget.h"
#include "alarmreq.h"
#include "computermanager.h"
#include "common.h"

ComputerDisplayWidget::ComputerDisplayWidget(Computer &computer, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ComputerDisplayWidget)
{
    ui->setupUi(this);
    this->computer = computer;
    ui->nameLabel->setText(computer.name);
    ui->ipLabel->setText(computer.ip);
    ui->remarkLabel->setText(computer.comment);
    if(computer.fromSource == ComputerFromSource_autoCreateByTCP)
    {
        ui->sourceLabel->setText("TCP自动添加");
    }
    else if(computer.fromSource == ComputerFromSource_importFromDB)
    {
        ui->sourceLabel->setText("数据库导入");
    }
    else
    {
        ui->sourceLabel->setText("手工添加");
    }

    reloadWithQueryConditions();

    displayLogs();

//    connect(parent,SIGNAL(delayGetClientAndAppInfo()),this,SLOT(delayGetClientInfo()));
//    connect(parent,SIGNAL(delayGetClientAndAppInfo()),this,SLOT(delayDisplayAppInfo()));

    getCurrentClientInfo();
    displayAppRunningInfos();
}

ComputerDisplayWidget::~ComputerDisplayWidget()
{
    delete ui;
}

void ComputerDisplayWidget::displayLogs()
{
    ui->logTableWidget->clearContents();

    int totalPageNum = logs.size() / pageSize + 1;
    ui->totalPageLable->setText("of " + int2QStr(totalPageNum));

    if(currentPageNum <= 0)
    {
        currentPageNum = 1;
    }
    else if (currentPageNum > totalPageNum)
    {
        currentPageNum = totalPageNum;
    }

    ui->pageNumLineEdit->setText(int2QStr(currentPageNum));
    ui->prePageButton->setEnabled(currentPageNum > 1);
    ui->nextPageButton->setEnabled(currentPageNum < totalPageNum);

    int i = 0;
    list<ComputerAlarmLog *>::iterator iter = logs.begin();
    list<ComputerAlarmLog *> playedLogs;
    for ( iter;i < currentPageNum * pageSize && iter != logs.end(); iter ++)
    {
        if(i >= (currentPageNum - 1) * pageSize)
        {
            playedLogs.push_back(*iter);
        }
        i++;
    }

    LOG_INFO("do display logs with count:%d, currentPageNum:%d", playedLogs.size(), currentPageNum);

    ui->logTableWidget->setRowCount(playedLogs.size());


    int y = 0;
    foreach (ComputerAlarmLog * log, playedLogs) {
        ui->logTableWidget->setItem(y,0,  new QTableWidgetItem(QString::number(log->id)));
        ui->logTableWidget->setItem(y,1,  new QTableWidgetItem(log->mode));
        ui->logTableWidget->setItem(y,2,  new QTableWidgetItem(log->sayType()));
        ui->logTableWidget->setItem(y,3,  new QTableWidgetItem(log->comment));
        ui->logTableWidget->setItem(y,4,  new QTableWidgetItem(log->time));
        ui->logTableWidget->setItem(y,5,  new QTableWidgetItem(boolToYesOrNo(log->isRead)));
        y++;
    }
}

void ComputerDisplayWidget::displayAppRunningInfos()
{
    list<AppRunningInfo> apps;

    if(f_success == gComputerManager.getAppRunningInfosFromIP(computer.ip.toStdString(), apps))
    {
        ui->appRunningInfoTable->clearContents();
        ui->appRunningInfoTable->setRowCount(apps.size());

        int y = 0;
        foreach (AppRunningInfo app, apps) {
            ui->appRunningInfoTable->setItem(y, 0, new QTableWidgetItem(QString::fromStdString(app.name)));
            ui->appRunningInfoTable->setItem(y, 1, new QTableWidgetItem(QString::fromStdString(app.type)));
            ui->appRunningInfoTable->setItem(y, 2, new QTableWidgetItem(QString::fromStdString(app.cfgInfo)));
            ui->appRunningInfoTable->setItem(y, 3, new QTableWidgetItem(QString::fromStdString(app.startCmd)));
            ui->appRunningInfoTable->setItem(y, 4, new QTableWidgetItem(QString::fromStdString(app.runningState)));
            y++;
        }
    }
    else
    {

    }
}

void ComputerDisplayWidget::drawCPU(list<float> cpus)
{
    if(ui->CPUInfoView->graphCount() == 0)
    {
        ui->CPUInfoView->addGraph();
        ui->CPUInfoView->yAxis->setLabel("占用率(%)");
        ui->CPUInfoView->xAxis->setRange(1, 20);
        ui->CPUInfoView->yAxis->setRange(1, 100);
    }

    int cpuChartIndex = 0;

    LOG_INFO("cpu.size == %d",cpus.size());
    QVector<double> x(cpus.size()), y(cpus.size());

    foreach (float cpu, cpus) {
        x[cpuChartIndex] = cpuChartIndex+1;
        y[cpuChartIndex] = cpu+1;
        cpuChartIndex++;

    }

    ui->CPUInfoView->graph(0)->setData(x, y, true);
    ui->CPUInfoView->replot();
}

void ComputerDisplayWidget::drawMemory(list<float> mems)
{
    if(ui->MemInfoView->graphCount() == 0)
    {
        ui->MemInfoView->addGraph();
        ui->MemInfoView->yAxis->setLabel("占用率(%)");
        ui->MemInfoView->xAxis->setRange(1, 20);
        ui->MemInfoView->yAxis->setRange(1, 100);
    }

    int memChartIndex = 0;

    QVector<double> x(mems.size()), y(mems.size());

    foreach (float mem, mems) {
        x[memChartIndex] = memChartIndex+1;
        y[memChartIndex] = mem+1;
        memChartIndex++;

    }

    ui->MemInfoView->graph(0)->setData(x, y, true);
    ui->MemInfoView->replot();

}

void ComputerDisplayWidget::drawDisks(list<DiskInfo> disks)
{

    static list<QWidget *> diskBGWidgets = list<QWidget *>();

    SafeClearListAndDelEle(QWidget, diskBGWidgets);

    int diskIndex = 0;

    foreach (DiskInfo disk, disks) {
        int widgetHeight = 420/disks.size();
        int widgetY = diskIndex *widgetHeight +10;
        diskIndex++;

        QWidget * diskBGWidget =  new QWidget(ui->DiskInfoView);
        diskBGWidgets.push_back(diskBGWidget);
        diskBGWidget->setGeometry(QRect(10, widgetY, 180, widgetHeight-10));
        diskBGWidget->setStyleSheet(QStringLiteral("background-color: rgb(240, 240, 240);"));
        diskBGWidget->show();

        QLabel *diskNameLabel = new QLabel(diskBGWidget);
        diskNameLabel->setText("磁盘"+disk.disk);
        diskNameLabel->setGeometry(QRect(10,0,170,(widgetHeight-10)/3));
        diskNameLabel->setStyleSheet(QStringLiteral("background-color: rgb(240, 240, 240);"));
        diskNameLabel->show();

        QProgressBar *diskBar = new QProgressBar(diskBGWidget);
        diskBar->setValue((1-disk.freeMB/disk.totalMB )*100);
        diskBar->setGeometry(QRect(10,(widgetHeight-10)/3,160,(widgetHeight-10)/3));
//        if(diskBar->value()>DISK_ALARM_THRESHOLD){
//            QPalette pe;
//            pe.setColor(QPalette::WindowText,Qt::red);
//            diskBar->setPalette(pe);
//        }
//         diskBar->setTextVisible(false);
        diskBar->show();

        QLabel *diskUsageLabel = new QLabel(diskBGWidget);
        QString freeMB = float2QStr((int)disk.freeMB/1024);
        QString totalMB = float2QStr((int)disk.totalMB/1024);
        diskUsageLabel->setText(freeMB+"GB可用,共"+totalMB+ "GB");
        diskUsageLabel->setGeometry(QRect(10,(widgetHeight-10)*2/3,170,(widgetHeight-10)/3));
        QPalette pa;
        pa.setColor(QPalette::WindowText,Qt::darkGray);
        diskUsageLabel->setPalette(pa);
        diskUsageLabel->show();


    }

}

void ComputerDisplayWidget::getQueryConditionsFromUI(QString *&alarmType, QString *&alarmMode, QString *&isRead)
{
    int alarmTypeIndex = ui->alarmTypeComboBox->currentIndex();
    int  alarmModeIndex = ui->alarmModeComboBox->currentIndex();
    int isReadIndex = ui->isReadComboBox->currentIndex();
    QString alarmModeText = ui->alarmModeComboBox->currentText();

    SafeDeleteObj(alarmType);
    SafeDeleteObj(alarmMode);
    SafeDeleteObj(isRead);

    if(isReadIndex == IS_READ_QUERY_MODE_UNLIMIT)
    {
        isRead = NULL;
    }
    else if(isReadIndex == IS_READ_QUERY_MODE_SUCCESSFUL)
    {
        isRead = new QString("1");
    }
    else
    {
        isRead = new QString("0");
    }

    if(alarmTypeIndex == AlarmReqType_UNLIMIT)
    {
        alarmType = NULL;
    }
    else if(alarmTypeIndex == AlarmReqType_CPU)
    {
        alarmType = new QString(QString::number(AlarmReqType_CPU));
    }
    else if(alarmTypeIndex == AlarmReqType_Memory)
    {
        alarmType = new QString(QString::number(AlarmReqType_Memory));
    }
    else if(alarmTypeIndex == AlarmReqType_HardDisk)
    {
        alarmType = new QString(QString::number(AlarmReqType_HardDisk));
    }
    else if(alarmTypeIndex == AlarmReqType_AppRestart)
    {
        alarmType = new QString(QString::number(AlarmReqType_AppRestart));
    }


    if(alarmModeIndex != 0)
    {
        alarmMode = new QString(alarmModeText);
    }
}

void ComputerDisplayWidget::reloadWithQueryConditions()
{
    currentPageNum = 1;
    SafeClearListAndDelEle(ComputerAlarmLog, logs);

    QString* alarmMode = NULL;
    QString* alarmType = NULL;
    QString* isRead = NULL;

    getQueryConditionsFromUI(alarmType, alarmMode, isRead);

    int logsCount;
    if(f_success == gDBService.loadComputerAlarmLogsCount(logsCount, &(computer.id), isRead, alarmType, alarmMode))
    {
        LOG_INFO("logCounts = %d", logsCount);
        int limit = -1;
        if(logsCount > MAX_DISPLAYED_LOGS_COUNT)
        {
            limit = MAX_DISPLAYED_LOGS_COUNT;
            QMessageBox::warning(this, "提示", "查询结果日志条数太多,只显示top1000");
        }

        if(f_success == gDBService.loadComputerAlarmLogs(logs, &(computer.id), isRead, alarmType, alarmMode, limit))
        {

            //will display logs
        }
        else
        {
            LOG_ERROR("try to get computer alarm logs  failed");
            QMessageBox::warning(this, "提示", "读取日志条数失败,数据库异常");
        }
    }
    else
    {
        LOG_ERROR("try to get computer alarm logs count failed");
        QMessageBox::warning(this, "提示", "读取日志条数失败,数据库异常");
    }

    displayLogs();
}

void ComputerDisplayWidget::on_pushButton_clicked()
{
    ComputerWindget * win = new ComputerWindget;
    win->setModal(false);
    win->prepareUpdate(computer);
    win->show();
}

void ComputerDisplayWidget::on_prePageButton_clicked()
{
    currentPageNum -= 1;
    displayLogs();
}

void ComputerDisplayWidget::on_nextPageButton_clicked()
{
    currentPageNum += 1;
    displayLogs();
}

void ComputerDisplayWidget::on_endPageButton_clicked()
{
    currentPageNum = logs.size()/pageSize + 1;
    displayLogs();
}

void ComputerDisplayWidget::on_firtPageButton_clicked()
{
    currentPageNum = 1;
    displayLogs();
}

void ComputerDisplayWidget::on_queryButton_clicked()
{
    reloadWithQueryConditions();
}

void ComputerDisplayWidget::on_deleteButton_clicked()
{
    if(QMessageBox::Yes == QMessageBox::information(this, "提示", "确认根据条件删除日志吗?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes))
    {
        QString* alarmMode = NULL;
        QString* alarmType = NULL;
        QString* isRead = NULL;

        getQueryConditionsFromUI(alarmType, alarmMode, isRead);

        if(f_success == gDBService.deleteComputerAlarmLogs(&(computer.id), isRead, alarmType, alarmMode))
        {
            QMessageBox::information(this, "提示", "删除日志成功");
            reloadWithQueryConditions();
            gComputerManager.onOneComputerAlarmLogsChanged(computer.id);
        }
        else
        {
            QMessageBox::warning(this, "警告", "删除日志失败,数据库错误");
        }
    }
}

void ComputerDisplayWidget::on_markButton_clicked()
{
    if(QMessageBox::Yes == QMessageBox::information(this, "提示", "确认根据条件标记日志为已读吗?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes))
    {
        QString* alarmMode = NULL;
        QString* alarmType = NULL;
        QString* isRead = NULL;

        getQueryConditionsFromUI(alarmType, alarmMode, isRead);

        if(f_success == gDBService.markUnreadComputerAlarmLogsToRead(&(computer.id), isRead, alarmType, alarmMode))
        {
            QMessageBox::information(this, "提示", "标记日志为已读成功");
            reloadWithQueryConditions();
            gComputerManager.onOneComputerAlarmLogsChanged(computer.id);
        }
        else
        {
            QMessageBox::warning(this, "警告", "标记日志为已读失败,数据库错误");
        }
    }
}

void ComputerDisplayWidget::on_remoteCtrlPushButton_clicked(bool checked)
{
    execCmdWithOutResult("mstsc /v " + computer.ip);
}

void ComputerDisplayWidget::getCurrentClientInfo()
{
    list<DiskInfo> lastDiskInfo;
    list<float> lastCPUUsages;
    list<float> lastMEMUsages;

    if(f_success == gComputerManager.getSystemRunningInfosFromIP(computer.ip.toStdString(), lastDiskInfo,lastCPUUsages,lastMEMUsages))
    {
        drawCPU(lastCPUUsages);
        drawMemory(lastMEMUsages);
        drawDisks(lastDiskInfo);
    }
}


void ComputerDisplayWidget::on_refreshRunningInfoPushButton_clicked()
{
    displayAppRunningInfos();
}

void ComputerDisplayWidget::on_refreshButton_clicked()
{
    getCurrentClientInfo();
}

void ComputerDisplayWidget::delayGetClientInfo()
{
    getCurrentClientInfo();
}

void ComputerDisplayWidget::delayDisplayAppInfo()
{
    displayAppRunningInfos();
}
